package com.xuexiang.xuidemo.provider;

import com.xuexiang.xui_lib.component.GridProvider;
import com.xuexiang.xui_lib.util.PixelMapUtils;
import com.xuexiang.xuidemo.ResourceTable;

import ohos.agp.components.*;
import ohos.agp.components.element.PixelMapElement;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public abstract class GridProviderImpl extends GridProvider {

    private final Context mContext;
    private List<Bean> itemList = new ArrayList<>();
    private final LayoutScatter mLayoutScatter;

    public GridProviderImpl(Context context) {
        this.mContext = context;
        mLayoutScatter = LayoutScatter.getInstance(context);
        createItem();
    }

    private void createItem() {
        Integer[] iconId = getIconId();
        String[] title = getTitle();
        if (iconId == null || iconId.length == 0 || title == null || title.length == 0) {
            return;
        }
        int count = iconId.length;
        if (iconId.length != title.length) {
            count = Math.min(iconId.length, title.length);
        }
        for (int i = 0; i < count; i++) {
            Bean bean = new Bean(title[i], iconId[i]);
            itemList.add(bean);
        }
    }

    @Override
    public int getCount() {
        return itemList.size();
    }


    @Override
    public Component getComponent(int position) {
        Component rootView = mLayoutScatter.parse(ResourceTable.Layout_grid_item_layout, null, false);
        Image image = (Image) rootView.findComponentById(ResourceTable.Id_image);
        Text title = (Text) rootView.findComponentById(ResourceTable.Id_title);
        Bean item = itemList.get(position);
        title.setText(item.title);
        image.setPixelMap(item.iconId);
        if (position == 5 ||position == 8){
            image.setScaleX(1.4F);
        }
        return rootView;
    }


    static class Bean {
        String title;
        int iconId;

        public Bean(String title, int iconId) {
            this.title = title;
            this.iconId = iconId;
        }
    }

    protected abstract String[] getTitle();

    protected abstract Integer[] getIconId();

}
